package com.lcz.mobilesafe.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.lcz.mobilesafe.R;
import com.lcz.mobilesafe.config.AppProtocol;
import com.lcz.mobilesafe.config.Constants;
import com.lcz.mobilesafe.domain.AppUpdateInfo;
import com.lcz.mobilesafe.utils.AppInfoUtils;
import com.lcz.mobilesafe.utils.FailedExceptionUtils;
import com.lcz.mobilesafe.utils.FileUtil;
import com.lcz.mobilesafe.utils.GsonUtils;
import com.lcz.mobilesafe.utils.ToastUtils;
import com.lcz.mobilesafe.widget.dialog.WaitDialog;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.Logger;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.download.DownloadListener;
import com.yolanda.nohttp.download.DownloadRequest;
import com.yolanda.nohttp.error.NetworkError;
import com.yolanda.nohttp.error.NotFoundCacheError;
import com.yolanda.nohttp.error.TimeoutError;
import com.yolanda.nohttp.error.URLError;
import com.yolanda.nohttp.error.UnKnownHostError;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.SimpleResponseListener;

import java.io.File;
import java.net.ProtocolException;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.lcz.mobilesafe.config.Constants.CODE_ENTER_HOME;
import static com.lcz.mobilesafe.config.Constants.CODE_JSON_ERROR;
import static com.lcz.mobilesafe.config.Constants.CODE_NET_ERROR;
import static com.lcz.mobilesafe.config.Constants.CODE_UPDATE_DIALOG;
import static com.lcz.mobilesafe.config.Constants.CODE_URL_ERROR;

/**
 * Created by hp on 2017/1/1.
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.tv_version)
    TextView tvVersion;
    private AppUpdateInfo updateInfo;//App更新信息
    private WaitDialog waitDialog;//请求网络等待框

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_UPDATE_DIALOG://弹出版本更新对话框
                    showUpdateDialog();
                    break;
                case CODE_ENTER_HOME://进入主页面
                    enterHome();
                    break;
            }
        }
    };

    private void showUpdateDialog() {
        new AlertDialog.Builder(this)
                .setTitle("最新版本：" + updateInfo.getVersionCode())
                .setMessage(updateInfo.getDescription())
                .setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        AppProtocol.download(MainActivity.this);
                    }
                })
                .setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        enterHome();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
            //返回键监听
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                enterHome();
            }
        }).show().setCanceledOnTouchOutside(false);//窗口外不消失，返回键消失
        //.setCancelable(false);//窗口外及返回键都不消失
    }

    /**
     * 进入主页
     */
    private void enterHome() {
        startActivity(new Intent(this, HomeActivity.class));
        finish();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        waitDialog = new WaitDialog(this);
        tvVersion.setText("版本号：" + AppInfoUtils.getVersionName());
        //判断是否需要检查版本更新
        SharedPreferences spf = getSharedPreferences("config", MODE_PRIVATE);
        if (spf.getBoolean("aotu_update", true)) {
            checkVersion();
        } else {
            //延迟1.5s发送消息进入主页
            handler.sendEmptyMessageDelayed(CODE_ENTER_HOME, 1500);
        }
    }

    /**
     * 从服务器读取数据进行版本信息校验
     */
    protected void checkVersion() {
        long startTime = System.currentTimeMillis();
        final Message message = Message.obtain();
        AppProtocol.requesDate_Get(Constants.URL_APPUPDATE, new SimpleResponseListener<String>() {
            @Override
            public void onStart(int what) {
                //请求开始显示一个dialog
                if (waitDialog != null && !waitDialog.isShowing()) {
                    waitDialog.show();
                }
            }

            @Override
            public void onSucceed(int what, Response<String> response) {
                super.onSucceed(what, response);
                System.out.println("MainActivity.onSucceed  String" + response.get());
                updateInfo = GsonUtils.getInstenceByJson(response.get(), AppUpdateInfo.class);
                if (updateInfo != null) {
                    int versionCode = updateInfo.getVersionCode();
                    //获取到的版本号比当前版本号大，说明有版本更新
                    if (versionCode > AppInfoUtils.getVersionCode()) {
                        message.what = CODE_UPDATE_DIALOG;
                    } else {
                        //无版本更新
                        message.what = CODE_ENTER_HOME;
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                FailedExceptionUtils.exception(response);
                message.what = CODE_ENTER_HOME;
            }

            @Override
            public void onFinish(int what) {
                super.onFinish(what);
                if (waitDialog != null && waitDialog.isShowing()) {
                    waitDialog.dismiss();
                }

            }
        });
        long endTime = System.currentTimeMillis();
        final long useTime = endTime - startTime;
        if (useTime < 2000) {//强制出现2s闪屏页时间
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000 - useTime);
                        //发送消息
                        handler.sendMessage(message);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        } else {
            //发送消息
            handler.sendMessage(message);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //暂停下载
        if (AppProtocol.mDownloadRequest != null) {
            AppProtocol.mDownloadRequest.cancel();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                enterHome();
                break;
        }
    }
}
